<template>
  <div class="credit-setting-container">
    <!-- Header Toolbar -->
    <div class="credit-header">
      <h1>积分设置</h1>
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '加载中...' : '刷新' }}
        </button>
        <button class="add-btn" @click="openAddDialog">
          添加
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      正在加载积分设置...
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <button @click="fetchCreditRules" class="retry-btn">重试</button>
    </div>

    <!-- 积分设置列表 -->
    <div v-else class="credit-content">
      <div v-for="(credit, index) in creditRules" :key="credit.id" class="credit-item">
        <div class="credit-info">
          <div class="credit-details">
            <div class="credit-header">
              <h3 class="credit-desc">{{ credit.behaviorDesc }}</h3>
              <span class="credit-range">{{ credit.levelRangeStart }} - {{ credit.levelRangeEnd }}</span>
            </div>
            <div class="credit-meta">
              <span class="credit-points">积分: {{ credit.points }}</span>
              <span class="credit-limit">{{ credit.limitDesc }}</span>
              <span class="credit-order">排序: {{ credit.sortOrder }}</span>
            </div>
            <div class="credit-time">
              创建时间: {{ formatDate(credit.createdAt) }}
            </div>
          </div>
        </div>
        
        <div class="credit-actions">
          <button 
            class="action-btn edit-btn" 
            @click="openEditModal(credit)"
            title="编辑"
          >
            编辑
          </button>
          <button 
            class="action-btn delete-btn" 
            @click="deleteCredit(credit.id)"
            title="删除"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 添加积分设置模态框 -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeAddModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>添加积分设置</h3>
          <button class="close-btn" @click="closeAddModal">&times;</button>
        </div>
        
        <form @submit.prevent="submitAddForm" class="modal-form">
          <div class="form-group">
            <label for="add-level-range-start">等级范围开始:</label>
            <input 
              id="add-level-range-start"
              v-model="addForm.levelRangeStart" 
              type="text" 
              required 
              placeholder="输入等级范围开始"
            />
          </div>
          
          <div class="form-group">
            <label for="add-level-range-end">等级范围结束:</label>
            <input 
              id="add-level-range-end"
              v-model="addForm.levelRangeEnd" 
              type="text" 
              required 
              placeholder="输入等级范围结束"
            />
          </div>
          
          <div class="form-group">
            <label for="add-behavior-desc">行为描述:</label>
            <input 
              id="add-behavior-desc"
              v-model="addForm.behaviorDesc" 
              type="text" 
              required 
              placeholder="输入行为描述"
            />
          </div>
          
          <div class="form-group">
            <label for="add-points">积分:</label>
            <input 
              id="add-points"
              v-model="addForm.points" 
              type="text" 
              required 
              placeholder="输入积分"
            />
          </div>
          
          <div class="form-group">
            <label for="add-limit-desc">限制描述:</label>
            <input 
              id="add-limit-desc"
              v-model="addForm.limitDesc" 
              type="text" 
              required 
              placeholder="输入限制描述"
            />
          </div>
          
          <div class="form-group">
            <label for="add-sort-order">排序:</label>
            <input 
              id="add-sort-order"
              v-model="addForm.sortOrder" 
              type="text" 
              required 
              placeholder="输入排序"
            />
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeAddModal" class="cancel-btn">取消</button>
            <button type="submit" class="submit-btn" :disabled="addFormSubmitting">
              {{ addFormSubmitting ? '添加中...' : '添加' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑积分设置模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑积分设置</h3>
          <button class="close-btn" @click="closeEditModal">&times;</button>
        </div>
        
        <form @submit.prevent="submitEditForm" class="modal-form">
          <div class="form-group">
            <label for="edit-level-range-start">等级范围开始:</label>
            <input 
              id="edit-level-range-start"
              v-model="editForm.levelRangeStart" 
              type="text" 
              required 
              placeholder="输入等级范围开始"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-level-range-end">等级范围结束:</label>
            <input 
              id="edit-level-range-end"
              v-model="editForm.levelRangeEnd" 
              type="text" 
              required 
              placeholder="输入等级范围结束"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-behavior-desc">行为描述:</label>
            <input 
              id="edit-behavior-desc"
              v-model="editForm.behaviorDesc" 
              type="text" 
              required 
              placeholder="输入行为描述"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-points">积分:</label>
            <input 
              id="edit-points"
              v-model="editForm.points" 
              type="text" 
              required 
              placeholder="输入积分"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-limit-desc">限制描述:</label>
            <input 
              id="edit-limit-desc"
              v-model="editForm.limitDesc" 
              type="text" 
              required 
              placeholder="输入限制描述"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-sort-order">排序:</label>
            <input 
              id="edit-sort-order"
              v-model="editForm.sortOrder" 
              type="text" 
              required 
              placeholder="输入排序"
            />
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeEditModal" class="cancel-btn">取消</button>
            <button type="submit" class="submit-btn" :disabled="editFormSubmitting">
              {{ editFormSubmitting ? '更新中...' : '更新' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="credit-footer">
      <!-- 页脚内容可以根据需要添加 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'

// 定义积分设置接口
interface CreditRule {
  id: string
  levelRangeStart: string
  levelRangeEnd: string
  behaviorDesc: string
  points: string
  limitDesc: string
  sortOrder: string
  createdAt: string
}

// API 响应接口
interface CreditRulesResponse {
  data: CreditRule[]
  msg: string
  status: number | boolean
  code: number
}

// 响应式数据
const creditRules = ref<CreditRule[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

// 模态框状态
const showAddModal = ref(false)
const showEditModal = ref(false)

// 表单数据
const addForm = ref({
  levelRangeStart: '',
  levelRangeEnd: '',
  behaviorDesc: '',
  points: '',
  limitDesc: '',
  sortOrder: ''
})

const editForm = ref({
  id: '',
  levelRangeStart: '',
  levelRangeEnd: '',
  behaviorDesc: '',
  points: '',
  limitDesc: '',
  sortOrder: ''
})

// 表单提交状态
const addFormSubmitting = ref(false)
const editFormSubmitting = ref(false)

// 刷新数据
const refreshData = () => {
  console.log('刷新积分设置数据')
  fetchCreditRules()
}

// 打开新增对话框
const openAddDialog = () => {
  console.log('打开新增积分对话框')
  showAddModal.value = true
  // 重置表单
  addForm.value = {
    levelRangeStart: '',
    levelRangeEnd: '',
    behaviorDesc: '',
    points: '',
    limitDesc: '',
    sortOrder: ''
  }
}

// 获取积分设置列表
const fetchCreditRules = async () => {
  try {
    loading.value = true
    error.value = null
    
    console.log('[DEBUG] Calling get_credit_rules from frontend')
    const response = await invoke<CreditRulesResponse>('get_credit_rules')
    console.log('[DEBUG] Received response:', response)
    
    // 验证响应
    if ((response.status === 1 || response.status === true) && 
        (response.code === 0 || response.code === 200)) {
      creditRules.value = response.data || []
      console.log('[DEBUG] Successfully loaded credit rules:', creditRules.value.length)
    } else {
      throw new Error(response.msg || '获取积分设置失败')
    }
  } catch (err) {
    console.error('[ERROR] Failed to fetch credit rules:', err)
    error.value = err instanceof Error ? err.message : '获取积分设置时发生未知错误'
  } finally {
    loading.value = false
  }
}

// 日期格式化
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN')
  } catch {
    return dateString
  }
}

// 添加积分设置相关方法
const closeAddModal = () => {
  showAddModal.value = false
  // 重置表单
  addForm.value = {
    levelRangeStart: '',
    levelRangeEnd: '',
    behaviorDesc: '',
    points: '',
    limitDesc: '',
    sortOrder: ''
  }
}

const submitAddForm = async () => {
  try {
    addFormSubmitting.value = true
    
    console.log('[DEBUG] Submitting add credit rule form:', addForm.value)
    
    const response = await invoke<CreditRulesResponse>('add_credit_rule', {
      levelRangeStart: addForm.value.levelRangeStart,
      levelRangeEnd: addForm.value.levelRangeEnd,
      behaviorDesc: addForm.value.behaviorDesc,
      points: addForm.value.points,
      limitDesc: addForm.value.limitDesc,
      sortOrder: addForm.value.sortOrder
    })
    
    console.log('[DEBUG] Add credit rule response:', response)
    
    if ((response.status === 1 || response.status === true) && 
        (response.code === 0 || response.code === 200)) {
      console.log('[DEBUG] Credit rule added successfully')
      closeAddModal()
      // 刷新列表
      await fetchCreditRules()
    } else {
      throw new Error(response.msg || '添加积分设置失败')
    }
  } catch (err) {
    console.error('[ERROR] Failed to add credit rule:', err)
    error.value = err instanceof Error ? err.message : '添加积分设置时发生错误'
  } finally {
    addFormSubmitting.value = false
  }
}

// 编辑积分设置相关方法
const openEditModal = (credit: CreditRule) => {
  editForm.value = {
    id: credit.id,
    levelRangeStart: credit.levelRangeStart,
    levelRangeEnd: credit.levelRangeEnd,
    behaviorDesc: credit.behaviorDesc,
    points: credit.points,
    limitDesc: credit.limitDesc,
    sortOrder: credit.sortOrder
  }
  showEditModal.value = true
}

const closeEditModal = () => {
  showEditModal.value = false
  // 重置表单
  editForm.value = {
    id: '',
    levelRangeStart: '',
    levelRangeEnd: '',
    behaviorDesc: '',
    points: '',
    limitDesc: '',
    sortOrder: ''
  }
}

const submitEditForm = async () => {
  try {
    editFormSubmitting.value = true
    
    console.log('[DEBUG] Submitting edit credit rule form:', editForm.value)
    
    const response = await invoke<CreditRulesResponse>('update_credit_rule', {
      creditId: editForm.value.id,
      levelRangeStart: editForm.value.levelRangeStart,
      levelRangeEnd: editForm.value.levelRangeEnd,
      behaviorDesc: editForm.value.behaviorDesc,
      points: editForm.value.points,
      limitDesc: editForm.value.limitDesc,
      sortOrder: editForm.value.sortOrder
    })
    
    console.log('[DEBUG] Update credit rule response:', response)
    
    if ((response.status === 1 || response.status === true) && 
        (response.code === 0 || response.code === 200)) {
      console.log('[DEBUG] Credit rule updated successfully')
      closeEditModal()
      // 刷新列表
      await fetchCreditRules()
    } else {
      throw new Error(response.msg || '更新积分设置失败')
    }
  } catch (err) {
    console.error('[ERROR] Failed to update credit rule:', err)
    error.value = err instanceof Error ? err.message : '更新积分设置时发生错误'
  } finally {
    editFormSubmitting.value = false
  }
}

// 删除积分设置
const deleteCredit = async (creditId: string) => {
  if (!confirm('确定要删除这个积分设置吗？')) {
    return
  }
  
  try {
    console.log('[DEBUG] Deleting credit rule:', creditId)
    // TODO: 实现删除功能，需要后端提供删除接口
    console.log('[INFO] Delete functionality needs to be implemented in backend')
    alert('删除功能待实现')
  } catch (err) {
    console.error('[ERROR] Failed to delete credit rule:', err)
    error.value = err instanceof Error ? err.message : '删除积分设置时发生错误'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('[DEBUG] CreditSettingPage mounted, fetching credit rules')
  fetchCreditRules()
})
</script>

<style scoped>
.credit-setting-container {
  background-color: var(--bg-primary);
  color: var(--text-primary);
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Header Toolbar 样式 */
.credit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
  padding: 16px 20px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.credit-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-btn,
.add-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.refresh-btn {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.refresh-btn:hover:not(:disabled) {
  background-color: var(--bg-card);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.add-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.add-btn:hover {
  background-color: var(--accent-primary-hover);
}

.loading, .error {
  text-align: center;
  padding: 48px 24px;
  font-size: 16px;
  color: var(--text-primary);
}

.error {
  color: var(--accent-danger);
}

.retry-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background-color: var(--accent-primary-hover);
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.credit-content {
  flex: 1;
  padding: 20px;
  padding-bottom: 40px;
  margin-bottom: 20px;
  overflow-y: auto;
  min-height: 0;
}

.credit-item {
  background-color: var(--bg-secondary);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.2s;
  border: 1px solid var(--border);
}

.credit-item:hover {
  background-color: var(--bg-card);
  border-color: var(--border-hover);
}

.credit-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.credit-details {
  flex: 1;
}

.credit-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}

.credit-desc {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.credit-range {
  background: var(--gradient-gold);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-weight: 700;
  font-size: 17px;
  padding-right: 16px;
}

.credit-meta {
  display: flex;
  gap: 24px;
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

.credit-points {
  color: var(--accent-primary);
  font-weight: 500;
}

.credit-limit-row {
  margin-bottom: 8px;
  font-size: 15px;
  color: var(--text-secondary);
}

.credit-limit {
  color: var(--text-secondary);
}

.credit-time {
  font-size: 12px;
  color: var(--text-muted);
}

.credit-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s;
}

.edit-btn {
  background-color: var(--accent-secondary);
  color: var(--text-inverse);
}

.edit-btn:hover {
  background-color: var(--accent-secondary-hover);
}

.delete-btn {
  background-color: var(--accent-danger);
  color: var(--text-inverse);
}

.delete-btn:hover {
  background-color: var(--accent-danger-hover);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--bg-card);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-card);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border);
}

.modal-header h3 {
  margin: 0;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-muted);
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: var(--text-primary);
}

.modal-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  background-color: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 4px;
  color: var(--text-primary);
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--border-focus);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.cancel-btn:hover {
  background-color: var(--bg-card);
}

.submit-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.submit-btn:hover:not(:disabled) {
  background-color: var(--accent-primary-hover);
}

.submit-btn:disabled {
  background-color: var(--text-muted);
  cursor: not-allowed;
}

.credit-footer {
  margin-bottom: 40px;
  padding-bottom: 40px;
}
</style>